package com.yayun.merchant.task;

import com.yayun.merchant.domain.AuctionItem;
import com.yayun.merchant.service.IAuctionItemService;
import com.yayun.merchant.websocket.AuctionWebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuctionTask {
    private static final Logger log = LoggerFactory.getLogger(AuctionTask.class);

    @Autowired
    private IAuctionItemService auctionItemService;

    /**
     * 每分钟检查需要开始的拍卖
     */
    @Scheduled(cron = "0 * * * * ?")
    public void checkAuctionStart() {
        List<AuctionItem> upcomingAuctions = auctionItemService.selectUpcomingAuctions();
        for (AuctionItem auction : upcomingAuctions) {
            try {
                auctionItemService.startAuction(auction.getId());
                // 发送WebSocket通知
                Map<String, Object> message = new HashMap<>();
                message.put("type", "auction_start");
                message.put("auctionId", auction.getId());
                message.put("productName", auction.getProduct().getName());
                AuctionWebSocket.sendMessage(auction.getId().toString(), message);
                log.info("拍卖{}已开始", auction.getId());
            } catch (Exception e) {
                log.error("开始拍卖{}失败：{}", auction.getId(), e.getMessage());
            }
        }
    }

    /**
     * 每分钟检查需要结束的拍卖
     */
    @Scheduled(cron = "0 * * * * ?")
    public void checkAuctionEnd() {
        List<AuctionItem> endingAuctions = auctionItemService.selectEndingAuctions();
        for (AuctionItem auction : endingAuctions) {
            try {
                auctionItemService.endAuction(auction.getId());
                // 发送WebSocket通知
                Map<String, Object> message = new HashMap<>();
                message.put("type", "auction_end");
                message.put("auctionId", auction.getId());
                message.put("productName", auction.getProduct().getName());
                message.put("winnerId", auction.getWinnerId());
                message.put("finalPrice", auction.getCurrentPrice());
                AuctionWebSocket.sendMessage(auction.getId().toString(), message);
                log.info("拍卖{}已结束", auction.getId());
            } catch (Exception e) {
                log.error("结束拍卖{}失败：{}", auction.getId(), e.getMessage());
            }
        }
    }
} 